<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Href\ImHrefAction;
use App\Admin\Grid\NGrid;
use App\Models\ShopUserMessageModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Filter;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class MessageController extends AdminController
{
    protected $title = '消息';

    /**
     * grid
     * @return NGrid
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    protected function grid(): NGrid
    {
        $userId = (int)request()->get('userId', 0);
        if ($userId <= 0) die;
        $grid = new NGrid(new ShopUserMessageModel);
        $grid->model()->leftJoin('shop_user', 'shop_user.user_id', 'shop_user_message.um_send_user_id')
            ->where('shop_user_message.um_receive_user_id', $userId)
            ->orderByDesc('shop_user_message.um_status')->orderByDesc('shop_user_message.um_id')
            ->select(['shop_user_message.*', 'shop_user.user_mobile', 'shop_user.user_avatar']);
        $grid->filter(function (Filter $filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function (Filter $filter) {
                $filter->equal('um_status', '状态')->select([1 => '已读', 2 => '未读']);
            });
            $filter->column(1 / 2, function (Filter $filter) {
                $filter->equal('shop_user-user_mobile', '手机号')->mobile();
            });
        });
        $grid->column('um_id', 'ID')->sortable();
        $grid->column('user_mobile', __('message.userMobile'))->display(function ($column) {
            if (is_null($column)) return '系统通知';
            else return $column;
        });
        $grid->column('um_status', '状态')->using([1 => '已读', 2 => '未读']);
        $grid->column('um_content', '消息');
        $grid->column('im_add_time', __('l.createdAt'))->display(function ($column) {
            return now()->timestamp($column)->toDateTimeString();
        });
        $grid->actions(function (Actions $action) {
            $action->disableDelete();
            $action->disableView();
            $action->disableEdit();
            $action->add(new ImHrefAction($action->row->um_send_user_id, $action->row->um_receive_user_id));
        });
        $grid->disableActions(false);
        return $grid;
    }
}
